<template>
  <view class="u-page">
    <!-- 修改高度为页面大小的80% -->
    <up-list style="height: 90vh; width: 100%;">
      <up-list-item 
        v-for="(item, index) in indexList" 
        :key="index"
      >
        <!-- 修改 up-cell 样式 -->
        <up-cell 
          :style="{
            marginBottom: '10rpx', // 增加每个 up-cell 之间的底部间距
            boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)', // 添加阴影效果，使其更立体
            borderRadius: '10rpx', // 圆角效果，增强立体感
            border: '1px solid #e0e0e0', // 添加边框效果
            transition: 'box-shadow 0.3s ease', // 添加过渡动画
            backgroundColor: item.sleepStatus === '0' ? '#86dff6' : '#fff'
          }"
        >
          <template #icon>
            <view style="display: flex; align-items: center; height: 80rpx;">
              <!-- 修改为倒序显示 -->
              <view style="margin-right: 10rpx; font-size: 32rpx;">{{ dataListlenght- index }}</view>
              <image :src="getBackgroundImage(item.sleepQuality)"  :style="{height: '100rpx', width: '100rpx'} "></image>
              <text :style="{marginLeft: '10rpx',fontSize: '32rpx', textAlign: 'left'}">
                {{ item.sleepQuality }}
              </text>
            </view>
          </template>
          <template #title>
            <view style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 80rpx;">
              <text style="text-align: left;">{{ item.startTime.split(' ')[0] }}</text>
              <text style="text-align: left;">{{ item.startTime.split(' ')[1] }}</text>
            </view>
          </template>
          <template #value>
            <view style="display: flex; flex-direction: column; align-items: flex-end; justify-content: center; height: 80rpx;">
              <!-- 根据 sleepStatus 显示不同内容 -->
              <text style="text-align: left;">
                {{ item.sleepStatus === '0' ? '正在进行中' : formatDuration(new Date(item.endTime).getTime() - new Date(item.startTime).getTime()) }}
              </text>
              <text style="margin-left: 10rpx; color: #007aff; cursor: pointer;" @click="getreport(item)">详情 ></text>
            </view>
          </template>
        </up-cell>
      </up-list-item>
      <view @click="loadMoreData">
        <up-loadmore
          :status="loadMoreStatus"
          :line="true"
          :loading-text-style="{ 'font-size': '32rpx', color: '#FF6600' }"
          :no-more-text-style="{ 'font-size': '32rpx', color: '#FF6600' }"
          :error-text-style="{ 'font-size': '32rpx', color: '#FF6600' }"
        ></up-loadmore>
      </view>
      <!-- 新增透明占位组件 -->
      <view style="height: 10vh; opacity: 0;"></view>
    </up-list>
   
    <tabbar :index="3"> </tabbar>
  
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { appListSleepReport } from '@/api/sleepReport'; 
import type { SleepReportRequestParams } from '@/types/sleepReport';
import { onShow } from '@dcloudio/uni-app';
// @ts-ignore
import { toast } from '@/uni_modules/uview-plus';

// 定义响应式数据
const indexList = ref<any[]>([]);
const loadMoreStatus = ref('loadmore');
const currentPage = ref(1); // 从第一页开始
const pageSize = ref(10);
const dataListlenght = ref(0);
// 加载更多数据
const loadMoreData = async () => {
  if( loadMoreStatus.value === 'no-more'){
    return;
  }
  try {
    const params: SleepReportRequestParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      orderByColumn: 'reportId',
      isAsc: 'desc'
    };
    const response = await appListSleepReport(params);
    // @ts-ignore
    const newData = response.rows; // 假设响应数据在 data 字段中
    // @ts-ignore
    dataListlenght.value = response.total;
    if (0<newData.length && newData.length <10){
      loadMoreStatus.value = 'no-more';
    }
    indexList.value = indexList.value.concat(newData);
    currentPage.value++;
  } catch (error) {
    console.error('获取睡眠报告数据失败:', error);
    loadMoreStatus.value = 'error';
  }
};

// 获取报告详情
const getreport = (item: any) => {
  if (item.sleepStatus === '0') {
    toast('正在监测中，睡眠报告未生成');
    return;
  }
  uni.navigateTo({
    url: `/pages/report/report?id=${item.reportId}`
  });
};

// 页面挂载时执行
onShow(async () => {
  try {
    await loadMoreData();
  } catch (error) {
    console.error('获取睡眠报告数据失败:', error);
  }
});

// 定义格式化持续时间的函数
const formatDuration = (duration: number) => {
  const hours = Math.floor(duration / (1000 * 60 * 60));
  const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((duration % (1000 * 60)) / 1000);
  return `${hours}小时 ${minutes}分钟 ${seconds}秒`;
};

// 根据睡眠质量计算背景色
const getBackgroundImage = (sleepQuality: number) => {
  if (sleepQuality > 80) {
    return '/static/img/report/quality1.png';

  } else if (sleepQuality >= 40 && sleepQuality <= 80) {
    return '/static/img/report/quality2.png';
  } else {
    return '/static/img/report/quality3.png';
  }
};
</script>

<style lang="scss" scoped>
.u-page {
  margin: 20rpx;
  background-color: #f0f2f4;
}

.up-list-item up-cell text {
  text-align: left;
}
</style>